package com.example.service;


import com.example.entity.Account;
import com.example.entity.Goods;
import com.example.entity.Score;
import com.example.mapper.GoodsMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Random;

/**
 * 业务层方法
 */
@Service
public class GoodsService {

    @Resource
    private GoodsMapper goodsMapper;

    @Resource
    private ScoreService scoreService;

    public void add(Goods goods) {
        goods.setScore("0");
        goods.setRecommend(false);
        goodsMapper.insert(goods);

    }

    @Transactional
    public void updateById(Goods goods) {

        double newScore;
        try {
            newScore = Double.parseDouble(goods.getScore());
        } catch (NumberFormatException e) {
            throw new RuntimeException("评分必须是数字");
        }

        // 2. 验证评分范围 (假设是0-5分)
        if (newScore < 0 || newScore > 5) {
            throw new RuntimeException("评分必须在0-5分之间");
        }

        // 3. 获取当前商品原始数据
        Goods originalGoods = goodsMapper.selectById(goods.getId());
        if (originalGoods == null) {
            throw new RuntimeException("商品不存在");
        }

        // 4. 解析当前评分信息
        double currentAverage = 0;
        int ratingCount = 0;

        if (originalGoods.getScore() != null && !originalGoods.getScore().isEmpty()) {
            try {
                currentAverage = Double.parseDouble(originalGoods.getScore());
                // 假设account字段存储评分人数（这里需要确认account字段的实际用途）
                ratingCount = originalGoods.getAccount() != null ?
                        Integer.parseInt(originalGoods.getAccount()) : 0;
            } catch (NumberFormatException e) {
                // 如果已有数据格式错误，则重置
                currentAverage = 0;
                ratingCount = 0;
            }
        }

        // 5. 计算新的平均分
        double totalScore = currentAverage * ratingCount + newScore;
        ratingCount++;
        double newAverage = totalScore / ratingCount;

        // 6. 更新商品信息（保留1位小数）
        DecimalFormat df = new DecimalFormat("#.0");
        originalGoods.setScore(df.format(newAverage));
        originalGoods.setAccount(String.valueOf(ratingCount)); // 使用account字段存储评分人数

        // 7. 更新商品信息
        goodsMapper.updateById(originalGoods);
    }


    public void deleteById(Integer id) {
        goodsMapper.deleteById(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            goodsMapper.deleteById(id);
        }
    }

    public Goods selectById(Integer id) {
        return goodsMapper.selectById(id);
    }

    public List<Goods> selectAll(Goods goods) {
        return goodsMapper.selectAll(goods);
    }

    public PageInfo<Goods> selectPage(Goods goods, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Goods> list = goodsMapper.selectAll(goods);
        return PageInfo.of(list);
    }

    public List<Goods> getRandomPictures() {
        int pageSize = 7; // 每次推荐7张图片
        int totalPictures = goodsMapper.countAllPictures(); // 获取总图片数量

        if (totalPictures < pageSize) {
            // 如果总图片数量小于7张，直接返回所有图片
            return goodsMapper.selectAllRecommend();
        }

        Random random = new Random();
        int randomOffset = random.nextInt(totalPictures - pageSize + 1); // 随机生成偏移量

        // 查询随机的7张图片
        return goodsMapper.selectRandomPictures(randomOffset, pageSize);
    }

    public void edit(Goods goods) {
        goodsMapper.updateById(goods);
    }
}
